import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store/index';
import Home from '../views/home/index.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/table-render',
    name: 'TableRender',
    meta: {
      auth: true,
    },
    // route level code-splitting
    // this generates a separate chunk (tableRender.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "tableRender" */ '../views/tableRender/index.vue'),
  },
  {
    path: '/directive',
    name: 'Directive',
    meta: {
      auth: true,
    },
    component: () => import(/* webpackChunkName: "directive" */ '../views/directive/index.vue'),
  },
  {
    path: '/vuex',
    name: 'Vuex',
    component: () => import(/* webpackChunkName: "vuex" */ '../views/vuex/index.vue'),
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

// 导航守卫
router.beforeEach((to, from, next) => {
  const { isAuthenticated } = store.getters;
  if (to.meta.auth && !isAuthenticated) {
    next({ name: 'Vuex' });
  } else {
    next();
  }
});

export default router;
